#!/usr/bin/env bash
function show_help() {
cat << EOF
   Usage: ${0##*/} [-p PACKAGE] [-l LANG] [-s] EMAIL
   Request key for EMAIL
   -p PACKAGE     Use package instead of Contrib
   -l LANG     Use LANG instead of the one from environment
   -t (test) Use staging environment
   -s (silent) Skip mailing
   EMAIL
EOF
}

if [ -z "$TOKEN" ]
then
  echo "TOKEN must be set in environment"
  exit 1
fi

package=Contrib
type=Licence
lang=en_US
endpoint=https://licencedb.myexpenses.mobi/users
silent=0

while getopts "p:l:ts" opt; do
    case "$opt" in
        p) package=$OPTARG
           ;;
        l) lang=$OPTARG
           ;;
        t) endpoint=http://127.0.0.1:3000/users
           ;;
        s) silent=1
           ;;
        '?')
            show_help >&2
            exit 1
            ;;
    esac
done
email=${@:$OPTIND:1}

words=( $email )
if [ ${#words[@]} -ne 1 ]
then
  echo "EMAIL must contain one word"
  show_help
  exit 1
fi

available_locales='ar bg cs de el en es eu fr he it ja kn ms pl pt ru tr vi'
available_addons='SplitTemplate History Budget Ocr WebUi CategoryTree CsvImport Synchronization AccountsUnlimited PlansUnlimited SplitTransaction Distribution Print AdFree Banking'

if [[ -z "${lang// }" || ! " $available_locales " =~ .*\ $lang\ .* ]]
then
    echo "lang must be one of $available_locales"
    exit 1
fi

if [[ " $available_addons " =~ .*\ $package\ .* ]]
then
  type=AddOn
fi

mapfile -t HTTP < <(curl -H "Authorization: Token $TOKEN" -H "Accept-Language: $lang" --silent --write-out "\n%{http_code}" -X POST $endpoint --data-urlencode email=$email -d package=$package -d type=$type -d silent=$silent)

status=${HTTP[-1]}

if [ ! "$status" -eq 200  ]; then
  echo "Error HTTP status $status"
  exit 1
fi

key=${HTTP[0]}

echo "$package für ${email}: $key"
